import React, { useState } from 'react';
import './App.css';

interface ApiResponse {
  success: boolean;
  result: string;
  error?: string;
}

function App() {
  const [imageUrl, setImageUrl] = useState('');
  const [query, setQuery] = useState('');
  const [result, setResult] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!imageUrl || !query) {
      setError('请填写所有必填字段');
      return;
    }

    setLoading(true);
    setError('');
    setResult('');

    try {
      const response = await fetch('/api/image-query', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          image_url: imageUrl,
          query: query
        }),
      });

      const data: ApiResponse = await response.json();

      if (data.success) {
        setResult(data.result);
      } else {
        setError(data.error || '请求失败');
      }
    } catch (err) {
      setError('网络错误，请检查后端服务是否运行');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>Model Evaluator</h1>
        <p>图像查询工具 - 基于阿里云通义千问API</p>
      </header>
      
      <main className="App-main">
        <form onSubmit={handleSubmit} className="query-form">
          <div className="form-group">
            <label htmlFor="imageUrl">图片地址 *</label>
            <input
              type="url"
              id="imageUrl"
              value={imageUrl}
              onChange={(e) => setImageUrl(e.target.value)}
              placeholder="请输入图片URL地址"
              required
            />
          </div>

          <div className="form-group">
            <label htmlFor="query">查询问题 *</label>
            <textarea
              id="query"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="请输入您想问的问题"
              rows={3}
              required
            />
          </div>

          <button type="submit" disabled={loading} className="submit-btn">
            {loading ? '查询中...' : '开始查询'}
          </button>
        </form>

        {error && (
          <div className="error-message">
            <h3>错误信息</h3>
            <p>{error}</p>
          </div>
        )}

        {result && (
          <div className="result-section">
            <h3>查询结果</h3>
            <div className="result-content">
              <pre>{result}</pre>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

export default App; 